﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class UpdateProcessHandler : IRequestHandler<UpdateProcessCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<Processinfo> _processinfoRepository;
        private  readonly IMapper mapper;
        private readonly ILogger<UpdateProcessHandler> _logger;

        public UpdateProcessHandler(IProcessRepository<Processinfo> processinfoRepository, IMapper mapper, ILogger<UpdateProcessHandler> logger)
        {
            _processinfoRepository = processinfoRepository;
            this.mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(UpdateProcessCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            
            try
            {
                // 验证数据是否存在
                var existingData = _processinfoRepository.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && x.IsDelete == false);
                if (existingData == null)
                {
                    result.Code = ErrorStatus.Fail;
                    result.Message = "要修改的工序不存在或已被删除";
                    result.Data = 0;
                    return result;
                }

                // 检查工序编号是否重复（排除当前记录）
                var duplicateCode = _processinfoRepository.GetAllAsync()
                    .FirstOrDefault(x => x.ProcessCode == request.ProcessCode && x.Id != request.Id && x.IsDelete == false);
                if (duplicateCode != null)
                {
                    result.Code = ErrorStatus.Fail;
                    result.Message = "工序编号已存在，请使用其他编号";
                    result.Data = 0;
                    return result;
                }

                var model = mapper.Map(request, existingData);
                
                // 更新数据
                var updateResult = await _processinfoRepository.UpdateAsync(model);
                
                if (updateResult > 0)
                {
                    result.Code = ErrorStatus.Success;
                    result.Message = "工序修改成功";
                    result.Data = updateResult;
                }
                else
                {
                    result.Code = ErrorStatus.Fail;
                    result.Message = "工序修改失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改工序失败，ID: {ProcessId}", request.Id);
                result.Message = "修改工序时发生错误";
            }
            return result;
        }
    }
}
